<template>
  <section>
    <!--工具条  高级查询-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="请输入关键字"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表-->
    <!--
      :data="menus" - 绑定数据
      highlight-current-row - 当前行高亮
      v-loading="listLoading" - 加载框=盲等框
      @selection-change="selsChange" - 选中改变的时候触发
      sortable - 是否排序
    -->
    <el-table :data="menus" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="菜单名称" width="150" sortable>
      </el-table-column>
      <el-table-column prop="component" label="组件路径" width="300" sortable>
      </el-table-column>
      <el-table-column prop="url" label="访问URL" width="150" sortable>
      </el-table-column>
      <!--<el-table-column prop="icon" label="图标" width="150" sortable>
      </el-table-column>-->
      <el-table-column prop="parent.name" label="上级菜单" width="150" sortable>
      </el-table-column>
       <!-- <el-table-column prop="intro" label="简介" width="150" sortable>
        </el-table-column>-->
      <el-table-column prop="state" label="菜单状态" width="100" sortable>
        <template scope="scope">
          <span style="color: green" v-if="scope.row.state">正常</span>
          <span style="color: red" v-else="scope.row.state">禁用</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next"
                     @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>


    <!--新增和修改界面-->
    <!--
     :title="title"  - 标题
     :visible.sync="saveFormVisible" - 是否显示对画框 - 默认不显示
     :close-on-click-modal="false" - 在对话框外面点击不关闭

     :model="saveForm"  -  绑定表单
     label-width="80px" -
     :rules="saveFormRules" - 表单的验证规则
     ref="saveForm" - 为当前对话框取名 - 方便验证表单
     auto-complete="off" - 自动完成
   -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="组件路径" prop="component">
          <el-input v-model="saveForm.component" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="访问URL" prop="url">
          <el-input v-model="saveForm.url" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <el-input v-model="saveForm.icon" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="排序" prop="index">
          <el-input-number v-model="saveForm.index" controls-position="right"
                           @change="handleChange" :min="1" :max="10"></el-input-number>
        </el-form-item>
        <el-form-item label="上级菜单">
        <!--  <el-input v-model="saveForm.parent_id" auto-complete="off"></el-input>-->
          <!--<el-select v-model="saveForm.parent_id" clearable placeholder="请选择">
            <el-option
                v-for="item in parents"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>-->

          <!--
           v-model="saveForm.parent_id" - 绑定数据 - 做回显 - 传值
             :options="deptTree" - 需要回显的菜单数
             :props="{ checkStrictly: true,label:'name',value:'id' }"
                 label:'name' - 显示哪一个值
                 value:'id' - 传递数据
             clearable - 可清理的
            回显机制： parent_id 与 deptTree中对象的id
            传值：将最新的菜单id 传递给 parent_id
         -->
          <el-cascader v-model="saveForm.parent_id"
                       :options="menuTree"
                       :props="{ checkStrictly: true,label:'name',value:'id' }"
                       clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <el-input v-model="saveForm.intro" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="菜单状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="true">启用</el-radio>
            <el-radio class="radio" :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>
import util from '../../common/js/util'
//import NProgress from 'nprogress'
import {getMenuListPage, removeMenu, batchRemoveMenu, editMenu, addMenu} from '../../api/api';

export default {
  data() {
    return {
      //1.数据列表相关数据模型
      menus: [], //显示分页列表数据
      listLoading: false, //关闭加载框

      //2.分页数据
      totals: 0, //总页数
      currentPage: 1, //当前页
      pageSize: 5, //当前页分页数据

      //3.高级查询
      keyword: "", //高级查询 -- 关键字

      //4.批量删除
      sels: [],//列表选中列

      //5.添加或修改
      title: "", //标题
      saveFormVisible: false,//添加和修改对话框是否显示
      saveLoading: false, //保存的忙等框 - 在提交按钮上
      saveFormRules: { //表单项验证规则
        name: [
          {required: true, message: '请输入菜单名称', trigger: 'blur'}
        ],
        index: [
          {required: true, message: '请输入排序索引', trigger: 'blur'}
        ],
        /*url: [
          {required: true, message: '请输入访问路径', trigger: 'blur'}
        ],
        component: [
          {required: true, message: '请输入组件路径', trigger: 'blur'}
        ]*/
      },

      //6.编辑界面数据
      saveForm: {
        id: null,
        name: '',
        component: '',
        url: '',
       /* icon: '',*/
        index: 1,
       /* intro: '',*/
        state: true,
        parent_id: null
      },

      //7.级联菜单树
      menuTree:[]
    }
  },
  methods: {
    //1.获取菜单列表数据
    getMenus() {
      let para = {
        "currentPage": this.currentPage, //当前页
        "pageSize": this.pageSize, //分页数据
        "keyword": this.keyword //高级查询
      };
      //开启加载框
      this.listLoading = true;
      this.$http.post("/menu", para).then(res => {
        //关闭加载框
        this.listLoading = false;
        //显示分页数据
        this.menus = res.data.data;
        //计算总数量
        this.totals = res.data.totals;
      }).catch(res => {
        this.$message.error("网络繁忙,请稍后再试");
      })
    },

    //2.点击分页的逻辑
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getMenus();
    },

    //3.点击排序
    handleChange(value) {
      this.saveForm.index = value;
    },

    //4.高级查询
    keywordQuery() {
      //重置到第一页
      this.currentPage = 1;
      //重新调用方法刷新列表
      this.getMenus();
    },

    //5.删除功能
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { //点击确认的时候
        //开启加载框
        this.listLoading = true;
        this.$http.delete("/menu/" + row.id).then(res => {
          //关闭加载框
          this.listLoading = false;
          //如果成功
          if (res.data.success) { //成功
            this.$message.success("删除成功");
            //对当前页的处理 -- 算出总页数
            let totalPage = Math.ceil(this.totals / this.pageSize);
            //如果当前页是最后一页并且是最后一个数据并且不是第一页
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              //到当前页上一页
              this.currentPage = this.currentPage - 1;
            }
            //再次调用方法
            this.getMenus();
          } else {
            this.$message.error("网络繁忙,请稍后重试【500】");
          }
        }).catch(res => {
          this.$message.error("网络繁忙,请稍后重试【400,404】");
        })
      }).catch(() => { //点击取消的时候
      });
    },

    //6.选项改变时触发
    selsChange: function (sels) {
      this.sels = sels;
    },

    //7.批量删除
    batchRemove: function () {
      var ids = this.sels.map(item => item.id)
      this.$confirm('确认删除该记录吗？', '提示', { //确认框
        type: 'warning'
      }).then(() => { //点击确认的时候
        //开启加载加载框
        this.listLoading = true;
        this.$http.patch("/menu", ids).then(res => {
          //关闭加载框
          this.listLoading = false;
          //如果成功
          if (res.data.success) { //成功
            //弹出成功消息
            this.$message.success("批量删除成功");
            //重置到第一页
            this.currentPage = 1;
            //重新调用方法
            this.getMenus();
          } else {
            this.$message.error("网络繁忙,请稍后再试【500】");
          }
        }).catch(res => {
          this.$message.error("网络繁忙,请稍后再试【400,404】");
        })
      }).catch(() => { //点击取消的时候
      });
    },

    //8.显示编辑界面
    handleEdit: function (index, row) {
      this.title = "编辑";
      //回显数据：避免以前的数据发生改变
      this.saveForm = Object.assign({}, row);
      this.getMenus();
      this.getMenuTree();
      //开启加载框
      this.saveFormVisible = true;
    },

    //9.显示新增界面
    handleAdd: function () {
      this.title = "新增";
      this.saveForm = {
        id: null,
        name: '',
        component: '',
        url: '',
        icon: '',
        index: 1,
        intro: '',
        state: true,
        parent_id: null
      };
      this.getMenus();
      this.getMenuTree();
      //开启加载框
      this.saveFormVisible = true;
    },

    //10.新增或者修改
    saveSubmit: function () {
      //所有的对话框中 的 名称为saveForm的对话框  验证上面的表单项验证通过就返回true
      this.$refs.saveForm.validate((valid) => { //表单验证
        if (valid) { //表单验证通过
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //开启加载框
            this.saveLoading = true;
            let para = Object.assign({}, this.saveForm);

            //对上级菜单做数据处理：选了上级菜单之后，有可能数据是这样的结构 [],[3,8],[8],[2,3,8]
            let arr =para.parent_id;
            console.log(arr);
            if (arr && arr.length==0){
                para.parent_id = null;
            }
            if (arr && arr.length>0){ //[3,8]
                para.parent_id = arr[arr.length-1];
            }

            this.$http.put("/menu", para).then(res => {
              //关闭加载框
              this.saveLoading = false;
              //关闭对话框
              this.saveFormVisible = false;
              if (res.data.success) { //成功
                //弹出成功消息
                this.$message.success("操作成功");
                //重新获得数据
                this.getMenus();
              } else {
                this.$message.error("网络繁忙,请稍后重试【500】");
              }
            }).catch(res => {
              this.$message.error("网络繁忙,请稍后重试【400,404】");
            })
          });
        }
      });
    },
    //11.查询所有上级菜单
    getMenuTree(){
      this.$http.get("/menu/menuTree").then(res =>{
        this.menuTree = res.data;
      })
    },
  },

  mounted() {
    this.getMenus();
  }
}
</script>

<style scoped>

</style>